package dao;

import common.utils.JdbcUtilsV1;
import entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class UserDao {
    public User login(String username, String password) {
        String sql = "select * from user where username=? and password=?";
        User user = JdbcUtilsV1.executeQueryOne(JdbcUtilsV1.getConnection(), User.class, sql, username, password);
        /*System.out.println("INFOS:");
        System.out.println(username+" "+password);*/
        return user;
    }

    public int register(String username, String password, int permission) {
        String sql = "insert into user(username,password,permission) values (?,?,?)";
        return JdbcUtilsV1.executeUpdate(sql, username, password, permission);
    }

    public User list(String username) {
        String sql = "select * from user where username=?";
        User user=JdbcUtilsV1.executeQueryOne(JdbcUtilsV1.getConnection(), User.class, sql, username);
        return user;
    }

    public int update(User user) {
        StringBuilder sql = new StringBuilder("update user set ");
        List<Object> params = new ArrayList<>();

        // 动态拼接非空字段
        if (user.getUsername() != null &&!user.getUsername().isEmpty()) {
            sql.append( "username = ?, ");
            params.add(user.getUsername());
        }
        if (user.getAddress() != null &&!user.getAddress().isEmpty()) {
            sql.append( "address = ?, ");
            params.add(user.getAddress());
        }
        if (user.getPhone() != null &&!user.getPhone().isEmpty()) {
            sql.append( "phone = ?, ");
            params.add(user.getPhone());
        }
        // 移除最后的逗号和空格
        if (!params.isEmpty()) {
            sql.delete(sql.length() - 2, sql.length());
        }
        // 添加WHERE条件
        sql.append(" where id = ?");
        params.add(user.getId());
        return (JdbcUtilsV1.executeUpdate(sql.toString(),params.toArray()));
    }

    public int updatePassword(int userId, String newPassword) {
        String sql = "update user set password = ? where id = ?";
        return JdbcUtilsV1.executeUpdate(sql, newPassword, userId);
    }
}
